package com.hzwl.controller

import com.hzwl.controller.vo.ReservoirAlgorithmVO
import com.hzwl.core.ExeHandle
import org.springframework.beans.factory.annotation.Value
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RestController
import java.io.File
import java.nio.file.Files
import java.nio.file.Paths

/**
 * TODO
 * @author lin
 */
@RestController
class Controller(
    val exeHandle: ExeHandle
) {
    @GetMapping
    fun hello(speed: String,hours:Int): Map<String, Any> {
        return exeHandle.handle(speed, hours)
    }


    @Value("\${reservoir.path}")
    lateinit var reservoirExePath: String

    @PostMapping("reservoir-algorithm")
    fun reservoirAlgorithm(@RequestBody reservoirAlgorithmVO: ReservoirAlgorithmVO): String {
        val args = listOf(
            "-rainfallRate", reservoirAlgorithmVO.rainfallRate.toString(),
            "-inflow", reservoirAlgorithmVO.inflow.toString(),
            "-outflow", reservoirAlgorithmVO.outflow.toString(),
            "-level", reservoirAlgorithmVO.level.toString(),
            "-temperature", reservoirAlgorithmVO.temperature.toString(),
            "-humidity", reservoirAlgorithmVO.humidity.toString(),
            "-windspeed", reservoirAlgorithmVO.windspeed.toString(),
            "-duringTime", reservoirAlgorithmVO.duringTime.toString(),
            "-mode", reservoirAlgorithmVO.mode.toString()
        )

        val workingDir = File(reservoirExePath).parentFile
        val process = ProcessBuilder(listOf(reservoirExePath) + args)
            .directory(workingDir)
            .redirectOutput(File("data.json"))
            .start()

        process.waitFor()
        val dataJsonPath = Paths.get("data.json")
        val jsonData = String(Files.readAllBytes(dataJsonPath))

        return jsonData
    }

}
